<?php

namespace app\admin\http\middleware;

use app\admin\model\AdminMenu;
use app\admin\traits\AdminAuth;
use think\exception\HttpResponseException;

class Auth
{
    use AdminAuth;
    /**
     * 当前url
     * @var string
     */
    protected $url;

    /**
     * 无需验证权限的url
     * @var array
     */
    public $authExcept = [];

    /**
     * 登录验证
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Redirect
     */
    public function handle($request, \Closure $next)
    {
        if ($this->isLogin()) {

            if (!$this->isNotNeedLogin($request)) {
                $this->url = parse_name(app('http')->getName()) . '/' .
                    parse_name($request->controller()) . '/' .
                    parse_name($request->action());

                if ($this->user->id !== 1 && !$this->authCheck($this->user, $request)) {
                    return redirect(url('/admin/error/index', ['msg' => '没有权限']));
                }
                if ($request->param('check_auth')) {
                    throw new HttpResponseException(success('验证权限成功',  URL_CURRENT,[]));
                }
                return $next($request);
            } else {
                return $next($request);
            }
        } else {
            if ($this->isNotNeedLogin($request)) {
                return $next($request);
            } else {

                return redirect('/admin/auth/login');
            }
        }
    }


    /**
     * 是否免登录验证
     * @param $request
     * @return bool
     */
    private function isNotNeedLogin($request)
    {
        $controller = 'app\\admin\\controller\\' . $request->controller() . 'Controller';
        $controller = new $controller(App());

        $this->authExcept = $controller->authExcept ?? [];
        if (empty($this->authExcept)) {
            return false;
        }
        $action = strtolower($request->action());
        $this->authExcept = array_map('strtolower', $this->authExcept);
        if (!in_array($action, $this->authExcept)) {
            return false;
        }
        return true;
    }
    /**
     * 权限检查
     * @param $user AdminUser
     * @return bool
     */
    public function authCheck($user, $request)
    {
        return in_array(strtolower($request->action()), $this->authExcept, true) || in_array($this->url, $user->auth_url, true);
    }


}
